package sn_log.worker;

import java.io.File;
import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;

import org.json.JSONObject;

import soar.basic.*;

import sn_log.share.*;

public class Worker extends Thread
{
    private String __CLASS__=Worker.class.getName();

    private DatagramSocket sock;

    public Worker(DatagramSocket sock)
    {//{{{
        this.sock=sock;
    }//}}}

    private boolean callcmd(String ip, String request)
    {//{{{
        try
        {
            JSONObject j=new JSONObject(request);
            if(!j.has("cmd"))
            {
                Errlog.add(__CLASS__+": request("+request+
                        ") cmd not found");
                return false;
            }
            String cmd=j.getString("cmd").toUpperCase();
            if(cmd.equals("LOG"))
            {
                if(!j.has("filename") || !j.has("msg"))
                {
                    Errlog.add(__CLASS__+": request("+request+
                            ") format error");
                    return false;
                }
                String filename=j.getString("filename");
                String msg=j.getString("msg");
                new LOG().call(ip, filename, msg);
            }
            else
            {
                Errlog.add(__CLASS__+": request("+request+
                        ") no cmd function");
                return false;
            }
        }
        catch(Exception e)
        {
            Errlog.add(__CLASS__+": request("+request+
                    ") invalid: "+e.toString());
            return false;
        }

        return true;
    }//}}}

    public void run()
    {//{{{
        byte[] buf=new byte[1024];
        DatagramPacket p=new DatagramPacket(buf, buf.length);
        String ip;
        String request;

        try
        {
            this.sock.setSoTimeout(2*1000);
        }
        catch(Exception e)
        {
        }

        while(true)
        {
            ip=null;
            request=null;
            try
            {
                this.sock.receive(p);
                ip=p.getAddress().getHostAddress();
                request=new String(buf, 0, p.getLength());
            }
            catch(SocketTimeoutException e)
            {
                //System.out.println(__CLASS__+": receive timeout");
            }
            catch(Exception e)
            {
                Errlog.add(__CLASS__+": receive fail: "+e.toString());
            }

            if(request != null)
            {
                callcmd(ip, request);
            }

            // 判断是否退出
            Operate operate=Operate.getInstance();
            if(operate.isShutdown())
            {
                operate.workerStop();
                Errlog.add(__CLASS__+": stop");
                break;
            }
        }
    }//}}}
}
